import { defineStore } from "pinia";
const useWs = defineStore('ws', {
    state: () => {
        return {
            ws: {},
            wsUrl: {},
            lockReconnect: false,
            data:{
                DL_MAC:0,//下行MAC速率
                DL_RLC:0,//下行RLC速率
                UL_MAC:0,//上行MAC速率
                UL_RLC:0,//上行RLC速率
                station_power:0,//基站功率
                inverter_active_power: 0,//逆变器功率
                pv_active_power: 0,//光伏板功率
                storage_active_power: 0,//储能输出功率
                storage_soc: 0//储能荷电状态（SOC）
            },
        };
    },
    actions: {
        createWebSocket(url) {
            try {
                console.log('try to connect');
                this.wsUrl = url;
                this.ws = new WebSocket(url);
                this.initEventHandle();
            } catch (e) {
                console.log('create websocket error');
                this.reconnect();
            }
        },
        initEventHandle() {
            this.ws.onclose = (closeEvent) => {
                console.log('监听到连接关闭');
                if (closeEvent.code != 1005) {
                    this.reconnect();
                }
            };
            this.ws.onerror = () => {
                console.log('监听到连接出错');
                this.reconnect();
            };
            this.ws.onopen = () => {
                console.log('监听到连接开启');
            };
            this.ws.onmessage = (event) => {
                //拿到任何消息都说明当前连接是正常的
                const down = JSON.parse(event.data);
                this.data = Object.assign(this.data,down)
            };
        },
        async connectToWebSocket() {
            if (this.ws.readyState == WebSocket.OPEN) {
                console.log('ws已连接');
            }else{
                this.createWebSocket('ws://localhost:8000/ws/data/')
            }
        },
        reconnect() {
            console.log('try to reconnect');
            this.ws.close();
            if (this.lockReconnect) return;
            this.lockReconnect = true;
            //没连接上会一直重连，设置延迟避免请求过多
            setTimeout(() => {
                this.lockReconnect = false;
                this.createWebSocket(this.wsUrl);
            }, 2000);
        },
    }
});

export default useWs;